package com.heima.comment.service.impl;

import com.heima.comment.service.CommentService;
import com.heima.model.comment.dtos.*;
import com.heima.model.comment.pojos.*;
import com.heima.model.comment.vos.WmCommentListVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.heima.common.constants.CommentConstants.*;


/**
 * @author JianKang
 * @create 2023-11-05 22:18
 */
@Service
@Slf4j
@Transactional
public class CommentServiceImpl implements CommentService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //1.校验参数
        if (dto == null || dto.getArticleId() == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.检查登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.保存评论
        ApComment apComment = new ApComment();
        apComment.setAuthorId(user.getId());
        apComment.setAuthorName("");
        apComment.setEntryId(dto.getArticleId());
        apComment.setChannelId(0);
        apComment.setType(COMMENT_TYPE_ARTICLE);
        apComment.setContent(dto.getContent());
        apComment.setImage("");
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag(COMMENT_FLAG_COMMON);
        apComment.setOrd(0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setStatus(COMMENT_STATUS_OPEN);


        mongoTemplate.save(apComment);

        kafkaTemplate.send("article-comment-add", dto.getArticleId().toString());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult loadComment(CommentDto dto) {
        //1.校验参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.条件查询
        Criteria criteria = Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate());
        Query query = Query.query(criteria).with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(10);
        List<CommentVo> commentVos = mongoTemplate.find(query, ApComment.class).stream().map(apComment -> {
            CommentVo commentVo = new CommentVo();
            BeanUtils.copyProperties(apComment, commentVo);
            ApCommentLike apCommentLike = mongoTemplate.findOne(Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(user.getId())), ApCommentLike.class);
            if (apCommentLike != null) {
                commentVo.setOperation(COMMENT_LIKE);
            }
            return commentVo;
        }).collect(Collectors.toList());
        return ResponseResult.okResult(commentVos);
    }

    @Override
    public ResponseResult likeComment(CommentLikeDto dto) {
        //1.校验参数
        if (dto == null || dto.getOperation() == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.检查登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.点赞或取消点赞
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        //3.1点赞
        if (apComment != null) {
            if (dto.getOperation().equals(COMMENT_LIKE)) {
                apComment.setLikes(apComment.getLikes() + 1);
                mongoTemplate.save(apComment);

                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentId(dto.getCommentId());
                mongoTemplate.save(apCommentLike);
            } else {
                //3.2取消点赞
                apComment.setLikes(apComment.getLikes() - 1);
                mongoTemplate.save(apComment);

                mongoTemplate.find(Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("authorId").is(user.getId())), ApCommentLike.class).forEach(apCommentLike -> mongoTemplate.remove(apCommentLike));
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult delComment(String commentId) {
        if (commentId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApComment apComment = mongoTemplate.findById(commentId, ApComment.class);
        if (apComment != null) {
            mongoTemplate.remove(apComment);
            ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }

    @Override
    public ResponseResult findNewsComments(ALLCommentListDto dto) {
        //1.校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询数据
        List<ApComment> apComments = mongoTemplate.findAll(ApComment.class);

        log.info("apcomments：{}", apComments);

//        if (dto.getBeginDate() != null) {
//            apComments = apComments.stream().filter(apComment -> apComment.getCreatedTime().getTime() >= dto.getBeginDate().getTime()).collect(Collectors.toList());
//        }
//        if (dto.getEndDate() != null) {
//            apComments = apComments.stream().filter(apComment -> apComment.getCreatedTime().getTime() <= dto.getEndDate().getTime()).collect(Collectors.toList());
//        }
        return ResponseResult.okResult(apComments);
    }


}
